import React from 'react';
import classNames from 'classnames'
import * as PropTypes from "prop-types";
import {CheckBoxStore} from "./index";
import {observer} from 'mobx-react'
import {StoreManager} from "@/stores";

@observer
export class CheckBox extends React.Component {

    static contextTypes = {
        formSettings: PropTypes.object
    }

    static propTypes = {
        name: PropTypes.oneOfType([PropTypes.string, PropTypes.symbol]).isRequired,
        label: PropTypes.string,
        value: PropTypes.any,
        checked: PropTypes.bool,
        disabled: PropTypes.bool,
        parentStore: PropTypes.object,
        validations: PropTypes.arrayOf(PropTypes.func)
    }

    static defaultProps = {
        validations: [],
        showErrors: true
    }

    constructor(props, context) {
        super(props, context)
        const parent = props.parentStore || (context.formSettings && context.formSettings.store)
        this.store = StoreManager.create(new CheckBoxStore(props), parent)
    }

    componentWillUnmount() {
        StoreManager.delete(this.store)
    }

    onChange = (e) => {
        this.store.toggle()
    }

    render() {
        const {className, label} = this.props
        const {disabled, checked} = this.store
        return <div className={classNames('checkbox', className)} disabled={disabled}>
            <label className={classNames('checkbox-button', {'checked': checked})} onClick={this.onChange.bind(this)}>
                <i className="checkbox-icon"></i>
                {label ? <span className="checkbox-label">{label}</span> : null}
            </label>
        </div>
    }
}
